<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\DormResultRequest;
use App\Models\V1\NewArrival;
use App\Models\V1\NewStudent;
use App\Models\V1\ResultClasses;
use App\Models\V1\ResultDorms;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;

class DormsResultController extends Controller
{
    //
    /**
     * 显示宿舍
     * 分配结果数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.result.dorms', $data);
    }


    /**
     * 获取迎新换届数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的宿舍
        //分配结果数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $arrival_code = $request->get('arrival_code');

        $from_select = $request->get('from_select');

        if ($from_select == false && empty($arrival_code)) {
            $arrival_code = $this->getArrivalCodes();
        }
        // 获取符合查询条件的宿舍
        //分配结果数据
        $data = $this->getDormResultList($currentPage, $rows, $arrival_code);
        $formatList = array();

        if (!$data->isEmpty()) {
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    //获取学生信息
                    $student = $this->getNewStudentByCode($item['exam_code']);
                    $formatItem['student_name'] = $student['name'];
                    $formatItem['exam_code'] = $student['exam_code'];
                    $formatItem['card_number'] = $student['card_number'];
                    //招生目录
                    $formatItem['enrollment_directory'] = $student['enrollment_directory'];
                    $clazz = $this->getNewStudentClassByCode($item['exam_code']);
                    $formatItem['class_name'] = empty($clazz) ? '' : $clazz;
                    $formatItem['dorm_code'] = $item['dorm_code'];
                    $formatItem['bed_number'] = $item['bed_number'];
                    $formatItem['building'] = $item['building'];
                    $formatItem['floor'] = $item['floor'];
                    $is_manager = $item['is_manager'];
                    $formatItem['is_manager'] = $this->formateIsManagerData($is_manager);
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['msg'] = '加载数据成功';

            }
        } else {
            $count = 0;
            $formatList = [];
            $response['msg'] = '暂无数据';
        }
        $response['code'] = 0;
        $response['count'] = $count;
        $response['data'] = $formatList;
        return $response;
    }

    /**
     * 进入单条宿舍
     * 分配结果数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        switch ($request->input('view')) {
            case 'addData':
                $students = $this->getNewStudents();
                $data['students'] = $students;
                return view('v1.form.dorms_result_item', $data);
                break;
            case 'viewData':
                $exam_code = $request->input('code');
                $dormResult = $this->getDormResultByCode($exam_code);
                $dorm['exam_code'] = $exam_code;
                $dorm['dorm_code'] = $dormResult->dorm_code;
                $dorm['bed_number'] = $dormResult->bed_number;
                $dorm['building'] = $dormResult->building;
                $dorm['floor'] = $dormResult->floor;
                $dorm['arrival_code'] = $dormResult->arrival_code;

                $is_manager = '否';
                if ($dormResult->is_manager) {
                    $is_manager = '是';
                }
                $dorm['is_manager'] = $is_manager;

                $dorm['updated_at'] = $dormResult->updated_at->format('Y-m-d H:i:s');
                $dorm['created_at'] = $dormResult->created_at->format('Y-m-d H:i:s');
                $student = $this->getNewStudentByCode($exam_code);
                $dorm['student_name'] = $student['name'];
                $dorm['card_number'] = $student['card_number'];
                //招生目录
                $dorm['enrollment_directory'] = $student['enrollment_directory'];
                $clazz = $this->getNewStudentClassByCode($exam_code);
                $dorm['class_name'] = empty($clazz) ? '' : $clazz;

                $data['dorm'] = $dorm;
                return view('v1.form.dorms_result_item', $data);
        }
    }

    /**
     * 显示迎新换届数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => $request->input('exam_code') . '宿舍分配失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['exam_code'] = 'bail|required';
            $rules['building'] = 'bail|required';
            $rules['floor'] = 'bail|required';
            $rules['dorm_code'] = 'bail|required';
            $rules['bed_number'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['exam_code.required'] = '学生代码不能为空';
            $messages['building.required'] = '楼栋不能为空';
            $messages['floor.required'] = '楼层不能为空';
            $messages['dorm_code.required'] = '宿舍号不能为空';
            $messages['bed_number.required'] = '床位号不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);
            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = $request->input('exam_code') . '宿舍分配成功！';
            }
        }

        return $response;
    }

    /**
     * 删除宿舍分配结果基本信息
     *
     * @param DormResultRequest $request
     * @return array
     */
    public function deleteData(DormResultRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '学生考试号[' . $request->input('code') . ']宿舍分配结果,删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateMajor($request);

            // 删除宿舍
            //分配结果信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '学生考试号[' . $request->input('code') . ']宿舍分配结果,删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除宿舍
     * 分配结果基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '宿舍分配结果批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '宿舍分配结果批量删除成功！';
            }
        }

        return $response;
    }


    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request)
    {

        $arrival_code = $this->getArrivalCodes();

        // 拼装新增数据数组
        $insertData = [
            'exam_code' => $request->input('exam_code'),
            'dorm_code' => $request->input('dorm_code'),
            'bed_number' => $request->input('bed_number'),
            'building' => $request->input('building'),
            'floor' => $request->input('floor'),
            'is_manager' => isset($request['is_manager']) ? $request->input('is_manager') : 0,
            'arrival_code' => $arrival_code,
        ];
        $rspObj = ResultDorms::updateOrCreate(['exam_code' => $request->input('exam_code')], $insertData);
        return $rspObj;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getDormResultList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = ResultDorms::orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = ResultDorms::where('arrival_code', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /***
     * 根据学生考试号获取学生详细信息
     * @param $code
     * @return mixed
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /**
     * 根据学生考试号获取学生班级名
     * @param $code
     * @return mixed
     */
    private function getNewStudentClassByCode($code)
    {
        $clazz = ResultClasses::where('exam_code', $code)->first();
        if (empty($clazz) || !isset($clazz)) {
            return '';
        }
        return $clazz->name;
    }

    /***
     * 获取所有学生
     * @param $code
     * @return mixed
     */
    private function getNewStudents()
    {
        $arrival_code = $this->getArrivalCodes();
        $students = NewStudent::where('arrival_code', $arrival_code)->select('exam_code', 'name')->get();
        return $students;
    }


    /***
     * 根据学生考试号宿舍分配信息
     * @param $code
     * @return mixed
     */
    private function getDormResultByCode($code)
    {
        $dorm = ResultDorms::where('exam_code', $code)->first();
        return $dorm;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn', true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新宿舍
     * 分配结果信息验证请求
     *
     * @param Request $request
     */
    private function validateDorm(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新宿舍
     * 分配结果信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');
        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = ResultDorms::where('exam_code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = ResultDorms::where('exam_code', $where)->delete();
        }

        return $rspObj;
    }

    /**
     * 格式化显示是否为舍长信息
     *
     * @param $val
     * @return string
     */
    private function formateIsManagerData($val)
    {
        $strFormat = '<span class="layui-bg-gray">否</span>';
        if ($val) {
            $strFormat = '<span class="layui-bg-green">是</span>';
        }
        return $strFormat;
    }

}
